app.controller('paramCtrl', function ($rootScope, $scope, $timeout, $http, $interval, URLService, FileUploader) {

    // 新增EMS代理默认值
    var DEFAULT_PROXY = {
        release: false,
        status: 1,
        emsId: 10000,
        emsIp: '127.0.0.1',
        emsPort: '54351',
        u2kPort: '52001',
        namespaceId: 'emsProxy',
        u2kName: 'admin',
        u2kPwd: 'admin',
        needRestart: true
    };

    //通用配置
    var options = {
        configFileInfoGridSchema: {
            model: {
                id: "itemId",
                parentId: "parentId",
                fields: {
                    itemId: {type: "number", nullable: true},
                    parentId: {nullable: true, type: "number"},
                    checked: {type: "boolean", nullable: true}
                },
                expanded: true
            }
        },
        filterable: {
            mode: 'row',
            operators: {
                string: {
                    contains: $scope.I18N.FILTER.contains,
                    eq: $scope.I18N.FILTER.eq
                },
                number: {
                    eq: I18N.FILTER.eq,
                    gt: I18N.FILTER.gt,
                    lt: I18N.FILTER.lt
                },
                date: {
                    eq: I18N.FILTER.eq,
                    gte: I18N.FILTER.after,
                    lte: I18N.FILTER.before
                }
            },
            messages: {
                info: $scope.I18N.FILTER.info,
                filter: $scope.I18N.FILTER.filter,
                clear: $scope.I18N.FILTER.clear,
                and: $scope.I18N.FILTER.and,
                or: $scope.I18N.FILTER.or
            }
        },
        cellFilterable: {
            cell: {
                suggestionOperator: "contains",
                showOperators: false,
                dataSource: new kendo.data.DataSource({
                    data: []
                })
            }
        },
        statusCellFilterable: {
            cell: {
                operator: "eq",
                showOperators: false,
                template: function (args) {
                    args.element.kendoDropDownList({
                        dataTextField: "text",
                        dataValueField: "value",
                        dataSource: [
                            {text: $scope.i18n.released, value: true},
                            {text: $scope.i18n.unReleased, value: false}
                        ]
                    });
                }
            }
        },
        needRestartCellFilterable: {
            cell: {
                operator: "eq",
                showOperators: false,
                template: function (args) {
                    args.element.kendoDropDownList({
                        dataTextField: "text",
                        dataValueField: "value",
                        dataSource: [
                            {text: $scope.i18n.yes, value: true},
                            {text: $scope.i18n.no, value: false}
                        ]
                    });
                }
            }
        },
        updateTimeCellFilterable: {
            cell: {
                operator: "gte",
                template: function (args) {
                    args.element.kendoDateTimePicker({
                        format: 'yyyy-MM-dd HH:mm:ss',
                        timeFormat: 'HH:mm:ss',
                        interval: 60
                    });
                }

            }
        }
    };

    $scope.options = {
        _gridOption: {
            height: '100%',
            resizable: true,
            scrollable: false,
            autoBind: true,
            noRecords: {
                template: '<span class="norecords">' + I18N.NORECORDS + '</span>'
            },
            editable: {
                mode: 'inline'
            },
            columns: [{
                field: 'release',
                title: $scope.i18n.releaseStatus,
                width: '140px',
                filterable: options.statusCellFilterable,
                template: kendo.template(angular.element('#release-cell-template').html())
            }, {
                field: 'keyName',
                title: 'key',
                width: '180px',
                filterable: options.cellFilterable
            }, {
                field: 'value',
                title: 'Value',
                width: '180px',
                filterable: options.cellFilterable
            }, {
                field: 'comment',
                title: $scope.i18n.comment,
                width: '120px',
                filterable: options.cellFilterable
            }, {
                field: "needRestart",
                title: $scope.i18n.needRestart,
                width: '120px',
                filterable: options.needRestartCellFilterable,
                template: function (dataItem) {
                    return dataItem.needRestart ? $scope.i18n.yes : $scope.i18n.no;
                }
            }, {
                field: "updateTime",
                title: $scope.i18n.releaseTime,
                width: '310px',
                filterable: options.updateTimeCellFilterable,
                template: function (dataItem) {
                    if (dataItem.updateTime) {
                        return kendo.toString(dataItem.updateTime, 'yyyy-MM-dd HH:mm:ss');
                    } else {
                        return '';
                    }
                }
            }, {
                title: $scope.i18n.operator,
                width: '100px',
                command: [{
                    name: 'edit',
                    text: {
                        edit: '',
                        update: '',
                        cancel: ''
                    }
                }]
            }],
            dataSource: {
                transport: {
                    //点击添加后保存，save事件触发后会触发create方法，若无create方法会报
                    // Cannot read property 'call' of undefined错误
                    create: function (options) {
                    },
                    //同create
                    update: function () {
                    },
                    //同create
                    destroy: function (options) {
                    }
                },
                schema: {
                    model: {
                        id: 'id',
                        fields: {
                            release: {
                                type: 'boolean',
                                editable: false
                            },
                            keyName: {
                                editable: false
                            },
                            needRestart: {
                                type: 'boolean',
                                editable: false
                            },
                            comment: {
                                type: 'string',
                                nullable: true
                            },
                            updateTime: {
                                type: 'date',
                                editable: false,
                                nullable: true
                            }
                        }
                    }
                },
                error: function () {
                    this.cancelChanges();
                }
            },
            filterable: options.filterable,
            dataBound: _dataBoundFun,
            cancel: _cancelFun,
            edit: _editFun,
            save: _updateConfigData
        },
        getGridOption: function (appId, namespaceId, app, namespace) {
            var gridOption = angular.copy(this._gridOption);
            gridOption.dataSource.transport.read = readFunFactory(appId, namespaceId, app, namespace);
            return gridOption;
        },
        //EMS代理设置表格
        emsProxyGridOption: {
            resizable: true,
            scrollable: false,
            sortable: false,
            noRecords: {
                template: '<span class="norecords">' + I18N.NORECORDS + '</span>'
            },
            editable: {
                mode: 'inline',
                createAt: 'bottom'
            },
            columns: [{
                field: 'release',
                title: $scope.i18n.releaseStatus,
                width: '140px',
                template: kendo.template(angular.element('#release-cell-template').html())
            }, {
                field: 'emsId',
                title: 'emsID',
                width: '100px'
            }, {
                field: 'emsName',
                title: $scope.i18n.emsName,
                width: '100px'
            }, {
                field: 'emsIp',
                title: $scope.i18n.proxyServiceIp,
                width: '100px'
            }, {
                field: 'emsPort',
                title: $scope.i18n.proxyServicePort,
                width: '120px'
            }, {
                field: 'u2kIp',
                title: $scope.i18n.u2kIP,
                width: '100px'
            }, {
                field: 'u2kPort',
                title: $scope.i18n.u2kPort,
                width: '140px'
            }, {
                field: 'u2kName',
                title: $scope.i18n.u2kUserName,
                width: '80px'
            }, {
                field: 'u2kPwd',
                title: $scope.i18n.u2kPassword,
                template: function (dataItem) {
                    //将密码用圆点显示
                    if (dataItem.u2kPwd === undefined) {
                        return;
                    }
                    var ps = '';
                    for (var i = 0; i < dataItem.u2kPwd.length; i++) {
                        ps += '▪'
                    }
                    return '<span>' + kendo.htmlEncode(ps) + '</span>';
                }
            }, {
                field: "needRestart",
                title: $scope.i18n.needRestart,
                width: '100px',
                template: function (dataItem) {
                    return dataItem.needRestart ? $scope.i18n.yes : $scope.i18n.no;
                }
            }, {
                title: $scope.i18n.operator,
                width: '120px',
                command: [{
                    name: ' ',
                    template: kendo.template($('#sync-btn').html())
                }, {
                    name: 'edit',
                    text: {
                        edit: '',
                        update: '',
                        cancel: ''
                    }
                }, {
                    name: ' ',
                    text: '',
                    className: 'iconFont-delete',
                    click: _deleteEmxProxy
                }]
            }],
            dataSource: {
                transport: {
                    read: _readEmsProxy,
                    destroy: function (options) {
                    },
                    create: function (options) {
                    },
                    update: function (options) {
                    }
                },
                schema: {
                    model: {
                        id: 'id',
                        fields: {
                            aid: {
                                type: 'number'
                            },
                            namespaceId: {
                                type: 'string',
                                defaultValue: DEFAULT_PROXY.namespaceId
                            },
                            emsId: {
                                type: 'number',
                                defaultValue: DEFAULT_PROXY.emsId,
                                editable: false
                            },
                            release: {
                                type: 'boolean',
                                defaultValue: DEFAULT_PROXY.release,
                                editable: false
                            },
                            status: {
                                type: 'number',
                                defaultValue: DEFAULT_PROXY.status
                            },
                            emsIp: {
                                type: 'string',
                                defaultValue: DEFAULT_PROXY.emsIp,
                                validation: {
                                    emsIpValidation: _emsIpValidation
                                }
                            },
                            u2kIp: {
                                type: 'string',
                                defaultValue: DEFAULT_PROXY.u2kIp,
                                validation: {
                                    u2kIpValidation: _u2kIpValidation
                                }
                            },
                            emsPort: {
                                type: 'string',
                                defaultValue: DEFAULT_PROXY.emsPort,
                                validation: {
                                    emsPortValidation: _emsPortValidation
                                }
                            },
                            emsName: {
                                type: 'string',
                                validation: {
                                    emsNameValidation: _emsNameValidation
                                }
                            },
                            u2kName: {
                                type: 'string',
                                defaultValue: DEFAULT_PROXY.u2kName,
                                validation: {
                                    u2kNameValidation: _u2kNameValidation
                                }
                            },
                            u2kPwd: {
                                type: 'string',
                                defaultValue: DEFAULT_PROXY.u2kPwd,
                                validation: {
                                    u2kPwdValidation: _u2kPwdValidation
                                }
                            },
                            u2kPort: {
                                type: 'string',
                                defaultValue: DEFAULT_PROXY.u2kPort,
                                validation: {
                                    u2kPortValidation: _u2kPortValidation
                                }
                            },
                            needRestart: {
                                type: 'boolean',
                                defaultValue: DEFAULT_PROXY.needRestart,
                                editable: false
                            }
                        }
                    },
                    parse: function (data) {
                        $.each(data, function (index, item) {
                            item.id = index;
                            item.aid = DEFAULT_PROXY.aid;
                            item.namespaceId = DEFAULT_PROXY.namespaceId;
                        });
                        return data;
                    }
                },
                error: function () {
                    this.cancelChanges();
                }
            },
            dataBound: _dataBoundFun,
            cancel: _cancelFun,
            edit: _editEmsProxyFun,
            save: _saveEmsProxy
        },
        //导入配置文件窗口
        importConfigWinOption: {
            title: $scope.i18n.importSysServerConfig,
            visible: false,
            resizable: false,
            draggable: false,
            modal: true,
            width: '80%',
            height: '80%',
            minWidth: 800,
            minHeight: 500,
            close: function () {
                var timer = $timeout(function () {
                    clearConfigWin();
                    $timeout.cancel(timer);
                }, 500);
            }
        },
        //配置文件信息表格
        configFileInfoGridOptions: {
            height: '100%',
            resizable: true,
            messages: {
                noRows: $scope.I18N.NORECORDS
            },
            columns: [
                {
                    headerTemplate: kendo.template(angular.element('#treelist-checkbox-head-template').html()),
                    template: kendo.template($("#treelist-checkbox-column-template").html()),
                    width: '16px'
                }, {
                    field: "itemId",
                    title: " ",
                    width: "15px",
                    expandable: true,
                    template: function () {
                        return '<div class="icon-btn"></div>';
                    }
                }, {
                    field: "key", title: "Key", width: "150px"
                }, {
                    field: "value",
                    title: "Value",
                    width: "150px"
                }, {
                    field: "comment",
                    title: $scope.i18n.comment,
                    width: "150px"
                }
            ],
            dataSource: {
                transport: {
                    read: _readConfigFileInfo
                },
                schema: options.configFileInfoGridSchema
            },
            dataBound: _configFileInfoGridDataBoundFun
        }
    };

    (function initPage() {
        //清除服务状态定时器
        $interval.cancel($rootScope.serverStatusTimer);
        //记录有修改的个数
        $scope.modifyItemNum = {};
        //正在导出配置文件
        $scope.exporting = false;
        //导入配置文件窗口中的"浏览"按钮
        $scope.uploader = new FileUploader();
        //文件解析错误信息提示
        $scope.configFileErrMsg = '';
        //配置文件信息表格数据源
        $scope.configFileInfoGridDs = [];
        //获取左侧导航（App列表）
        getNavigation();
        //通过该方式初始化的kendoTreeList控件每次展开/收起子项 不会改变表格DOM，可实现子项样式修改
        $('#configFileInfoGrid').kendoTreeList(
            $scope.options.configFileInfoGridOptions
        );
    })();

    $scope.events = {
        //发布按钮点击事件
        publishBtnClickEvt: function (appId, namespaceId, app, namespace) {
            if (appId === DEFAULT_PROXY.aid && namespaceId === DEFAULT_PROXY.namespaceId) {
                //在ng-repeat指令内初始化的kendoGrid无法通过$scope拿到
                var grid = $('#grid_' + appId + '_' + namespaceId).data('kendoGrid');
                var dataItems = grid.dataSource.data();
                if (dataItems.length === 0 || (dataItems.length === 1 && !angular.isNumber(dataItems[0].id))) {
                    //无数据时，提示需添加ems才能发布
                    Ut.dialog.tip($scope.i18n.tip.noEms);
                } else {
                    publishEmsConfig(appId, namespaceId);
                }
            } else {
                publishConfig(appId, namespaceId, app, namespace);
            }
        },
        //导出配置文件按钮点击事件
        exportBtnClickEvt: function () {
            $scope.exporting = true;
            var url = URLService.getURL('exportConfig');
            $http.post(url).success(function (response) {
                $scope.exporting = false;
                if (response.success) {
                    Ut.urlUtils.openUrl(response.data);
                } else {
                    Ut.dialog.errMsg(response.errorMsg);
                }
            });
        },
        //导入配置文件按钮点击事件
        importBtnClickEvt: function () {
            $scope.importConfigWin.center().open();
        },
        //本地文件选择 改变事件
        selectedFileChangedEvt: function (ele) {
            clearConfigWin();
            processConfigFile(ele);
        },
        //导入配置文件窗口 确定按钮点击事件
        confirmBtnEvt: function () {
            processSelectedConfigData();
        },
        //导入配置文件窗口 取消按钮点击事件
        cancelBtnEvt: function () {
            $scope.importConfigWin.close();
        },
        //导入配置文件窗口 配置文件信息表格checkbox点击事件
        checkboxClickEvt: function (id, e) {
            var checked = e.checked;
            updateCheckboxStatus(id, checked);
        },
        //导入配置文件窗口 配置文件信息表格 表头checkbox点击事件
        headCheckboxClickEvt: function (id, e) {

            if ($scope.configFileInfoGridDs.length === 0) {
                angular.element('#headCheckbox').prop("checked", false);
            }
            var checked = e.checked;
            updateCheckboxStatus(id, checked);
        },
        syncEmxProxyBtnClickEvt: function (emsId) {
            syncEmxProxy(emsId);
        },
        //新增EMS代理
        addEmsBtnClickEvt: function (appId, namespaceId) {
            processModifyItemNum(DEFAULT_PROXY.aid, DEFAULT_PROXY.namespaceId);
            var grid = $('#grid_' + appId + '_' + namespaceId).data('kendoGrid');
            grid.addRow();
        },
        //一键发布按钮点击事件
        batchReleaseBtnClickEvt: function () {
            batchRelease();
        },
        //
        stopProp:function (e) {
            e.stopPropagation();
        }
    };

    //获取导航项
    function getNavigation() {
        var url = URLService.getURL('getApps');
        kendo.ui.progress(angular.element('.loading'), true);
        $http.post(url).success(function (response) {
            kendo.ui.progress(angular.element('.loading'), false);
            if (response.success) {
                $scope.apps = response.data;
                $scope.modifyItemNum = {};
                angular.forEach($scope.apps, function (app) {
                    $scope.modifyItemNum['n' + app.id] = {sum: 0};
                    if (app.emsProxy) {
                        DEFAULT_PROXY.aid = app.id;
                    }
                });
            } else {
                $scope.apps = [];
                Ut.dialog.errMsg(response.errorMsg);
            }
        });
    }

    //一键发布所有
    function batchRelease() {
        var url = URLService.getURL('batchRelease');
        $http.get(url).success(function (response) {
            if (response.success) {
                Ut.dialog.tip($scope.i18n.publishSuccess);
                //在ng-repeat指令内初始化的kendoGrid无法通过$scope拿到
                angular.forEach($scope.apps, function (app) {
                    var appId = app.id;
                    angular.forEach(app.params, function (param) {
                        var namespaceId = param.id;
                        $('#grid_' + appId + '_' + namespaceId).data('kendoGrid').dataSource.read();
                        if(appId===DEFAULT_PROXY.aid){
                            $('#grid_' + appId + '_emsProxy').data('kendoGrid').dataSource.read();
                        }
                    });
                })
            } else {
                Ut.dialog.errMsg(response.errorMsg);
            }
        });
    }

    //发布配置
    function publishConfig(appId, namespaceId, app, namespace) {
        var url = URLService.getURL('publishConfig');
        $http.post(url, {
            appId: app,
            namespace: namespace
        }).success(function (response) {
            if (response.success) {
                Ut.dialog.tip($scope.i18n.publishSuccess);
                //在ng-repeat指令内初始化的kendoGrid无法通过$scope拿到
                $('#grid_' + appId + '_' + namespaceId).data('kendoGrid').dataSource.read();
            } else {
                Ut.dialog.errMsg(response.errorMsg);
            }
        });
    }

    //构造 获取参数数据方法
    function readFunFactory(appId, namespaceId, app, namespace) {
        return function (options) {
            processModifyItemNum(appId, namespaceId);

            var url = URLService.getURL('getConfigData');
            $http.post(url, {appId: app, namespace: namespace}).success(function (response) {
                if (response.success) {
                    options.success(response.data);
                } else {
                    options.success([]);
                    Ut.dialog.errMsg(response.errorMsg);
                }
            });
        }
    }

    //处理修改项计数
    function processModifyItemNum(appId, namespaceId) {
        //重置本表格修改项计数
        var curApp = $scope.modifyItemNum['n' + appId];
        var curGridId = 'n_' + namespaceId;
        //非初始化表格时查询，需减去本表格原有修改项数目，清零后在dataBound方法中重新统计
        if (angular.isNumber(curApp[curGridId])) {
            curApp.sum -= curApp[curGridId];
        }
        curApp[curGridId] = 0;
    }

    //处理本地配置文件
    function processConfigFile(ele) {
        $scope.configFile = ele.files[0];
        //读取选择的本地文件
        var reader = new FileReader();
        reader.onload = function (e) {
            var jsonString = e.target.result;
            var configObj;
            if (e.target.readyState == FileReader.DONE) {
                try {
                    configObj = angular.fromJson(jsonString);
                    var checkOk = configFileDataConversion(configObj);
                    if (checkOk) {
                        var grid = $('#configFileInfoGrid').data('kendoTreeList');
                        grid.dataSource.read();
                        grid.resize();
                    }
                } catch (e) {
                    $scope.configFileErrMsg = $scope.i18n.tip.jsonFormatWrong;
                }

            }
            $scope.$apply();
        };
        reader.readAsText($scope.configFile);

        //保证下次选择同样文件名的文件时，能正常进入该方法
        ele.value = '';

        //传播Model的变化。
        $scope.$apply();
    }

    //将JSON格式转换为kendoTreeList dataSource要求的数据格式
    function configFileDataConversion(configObj) {
        var convertOk = true;
        //每行数据项的id
        var itemId = 0;
        if (angular.isArray(configObj)) {
            angular.forEach(configObj, function (appItem, appItemIndex) {
                if (convertOk) {
                    if (angular.isArray(appItem.namespace)) {
                        angular.forEach(appItem.namespace, function (namespace, namespaceIndex) {
                            var parentId;
                            if (convertOk) {
                                if (angular.isArray(namespace.item)) {
                                    angular.forEach(namespace.item, function (item, itemIndex) {
                                        var data;
                                        if (itemIndex === 0) {
                                            data = {
                                                itemId: itemId,
                                                key: appItem.appName + ' | ' + namespace.namespace,
                                                appName: appItem.appName,
                                                appId: appItem.appId,
                                                appComment: appItem.appComment,
                                                namespace: namespace.namespace
                                            };
                                            $scope.configFileInfoGridDs.push(data);
                                            parentId = itemId;
                                            itemId++;
                                        }
                                        data = {
                                            itemId: itemId,
                                            parentId: parentId,
                                            key: item.keyName,
                                            value: item.value,
                                            comment: item.itemComment,
                                            appName: appItem.appName,
                                            appId: appItem.appId,
                                            appComment: appItem.appComment,
                                            namespace: namespace.namespace,
                                            namespaceComment: namespace.namespaceComment,
                                            keyName: item.keyName,
                                            needRestart: item.needRestart,
                                            itemComment: item.itemComment
                                        };
                                        $scope.configFileInfoGridDs.push(data);
                                        itemId++;
                                    })
                                } else {
                                    convertOk = false;
                                    $scope.configFileErrMsg = $scope.i18n.tip.jsonFormatWrong;
                                }
                            }
                        })
                    } else {
                        convertOk = false;
                        $scope.configFileErrMsg = $scope.i18n.tip.jsonFormatWrong;
                    }
                }
            });
        } else {
            convertOk = false;
            $scope.configFileErrMsg = $scope.i18n.tip.jsonFormatWrong;
        }
        return convertOk;
    }

    //更新checkbox勾选状态
    function updateCheckboxStatus(id, checked) {
        var grid = $('#configFileInfoGrid').data('kendoTreeList');
        var dataSource = grid.dataSource.view();
        //表头checkbox
        if (id === 'headCheckbox') {
            //更新表格内所有数据项checkbox选中状态
            angular.forEach(dataSource, function (data) {
                data.checked = checked;
                angular.element('#n' + data.id).prop("checked", checked);
            })
        }
        var targetItem = grid.dataSource.get(id);
        if (!targetItem) {
            return;
        }
        targetItem.checked = checked;

        // 子项
        if (angular.isNumber(targetItem.parentId)) {
            var parentItem = grid.dataSource.get(targetItem.parentId);
            pudateParentItemStatus(dataSource, parentItem);
        } else {// 父项
            //更新子项
            angular.forEach(dataSource, function (data) {
                if (data.parentId === targetItem.itemId) {
                    data.checked = checked;
                    angular.element('#n' + data.id).prop("checked", checked);
                }
            })
        }
        pudateHeadItemStatus(dataSource);
    }

    //根据子项checkbox状态更新父项checkbox状态
    function pudateParentItemStatus(dataSource, parentItem) {
        var allChecked = true;
        angular.forEach(dataSource, function (data) {
            if (data.parentId === parentItem.itemId) {
                if (allChecked) {
                    allChecked = allChecked && data.checked;
                }
            }
        });
        angular.element('#n' + parentItem.id).prop("checked", allChecked);
    }

    //根据表格内所有行checkbox状态更新表头checkbox状态
    function pudateHeadItemStatus(dataSource) {
        var allChecked = true;
        angular.forEach(dataSource, function (data) {
            if (allChecked) {
                allChecked = allChecked && data.checked;
            }
        });
        angular.element('#headCheckbox').prop("checked", allChecked);
    }

    //处理勾选的配置数据
    function processSelectedConfigData() {
        var configData = [];
        var grid = $('#configFileInfoGrid').data('kendoTreeList');
        var dataSource = grid.dataSource.view();
        angular.forEach(dataSource, function (data) {
            if (data.checked) {
                configData.push(data);
            }
        });
        if (configData.length === 0) {
            $scope.configFileErrMsg = $scope.i18n.tip.noSelect;
        } else {
            importConfigData(configData);
        }
    }

    //导入配置数据
    function importConfigData(configData) {
        var url = URLService.getURL('importConifg');
        $http.post(url, configData).success(function (response) {
            if (response.success) {
                $scope.importConfigWin.close();
                getNavigation();
            } else {
                Ut.dialog.errMsg(response.errorMsg);
            }
        });
    }

    //同步ems
    function syncEmxProxy(emsId) {
        var url = URLService.getURL('syncEms');
        $http.post(url, {
            emsId: emsId
        }).success(function (response) {
            if (response.success) {
                Ut.dialog.tip($scope.i18n.tip.syncEms);
            } else {
                Ut.dialog.errMsg(response.errorMsg);
            }
        });
    }

    //发布ems
    function publishEmsConfig(appId, namespaceId) {
        var url = URLService.getURL('publishEms');
        $http.post(url).success(function (response) {
            if (response.success) {
                Ut.dialog.tip($scope.i18n.publishSuccess);
                $('#grid_' + appId + '_' + namespaceId).data('kendoGrid').dataSource.read();
            } else {
                Ut.dialog.errMsg(response.errorMsg);
            }
        });
    }

    //为按钮添加提示信息
    function addBtnTitle(row) {
        row.find('.k-grid-update').each(function (rowNum, btn) {
            angular.element(btn).attr('title', $scope.I18N.OK);
        });
        row.find('.k-grid-cancel').each(function (rowNum, btn) {
            angular.element(btn).attr('title', $scope.I18N.CANCEL);
        });
    }

    //重置配置文件窗口中相关变量
    function clearConfigWin() {
        $scope.configFileErrMsg = '';
        $scope.configFile = {};
        angular.element('#headCheckbox').prop("checked", false);
        $scope.configFileInfoGridDs = [];
        $('#configFileInfoGrid').data('kendoTreeList').dataSource.read();
    }

    function _editEmsProxyFun(e) {
        var grid = e.sender;
        var row = e.container;
        //为确定、取消按钮添加提示
        addBtnTitle(row);

        if (e.model.isNew()) {
            // 新增ems代理时，为某些field设置默认值
            var gridData = grid.dataSource.view();
            var targetRowData = gridData[gridData.length - 1];
            targetRowData.aid = DEFAULT_PROXY.aid;
            targetRowData.u2kPwd = DEFAULT_PROXY.u2kPwd;
            // 当前正在新增的row也在grid的dataSource中，所以最后一行数据其实是倒数第二行
            if (gridData.length > 1) {
                var lastRowData = gridData[gridData.length - 2];
                targetRowData.emsId = lastRowData.emsId + 1;
                row.find('[ng-bind="dataItem.emsId"]').html(targetRowData.emsId);
            }
            targetRowData.emsName = $scope.i18n.ems + (targetRowData.emsId - DEFAULT_PROXY.emsId + 1);
            row.find("input[name=emsName]").val(targetRowData.emsName).trigger('change');
            row.find("input[name=u2kPwd]").val(targetRowData.u2kPwd);
        }

        row.find("input[name=emsName]").attr("spellcheck", false);
        row.find("input[name=u2kPwd]").attr("type", "password");
        row.find("input[name=u2kPwd]").attr("autocomplete", "new-password");

    }

    function _editFun(e) {
        var row = e.container;
        addBtnTitle(row);
    }

    //读取EMS代理设置表格数据
    function _readEmsProxy(options) {
        var url = URLService.getURL('readEmsProxy');
        $http.get(url).success(function (res) {
            if (res.success) {
                processModifyItemNum(DEFAULT_PROXY.aid, DEFAULT_PROXY.namespaceId);
                options.success(res.data);
            } else {
                options.success([]);
                Ut.dialog.warn(res.errorMsg || $scope.i18n.message.readEmsDataError);
            }
        });
    }

    //保存EMS代理配置
    function _saveEmsProxy(e) {
        //点击保存按钮会调用_dataBoundFun,先清空修改项计数，防止计数闪变
        processModifyItemNum(DEFAULT_PROXY.aid, DEFAULT_PROXY.namespaceId);

        var data = e.model;
        var grid = e.sender;
        angular.forEach(data, function (value, key) {
            if (angular.isString(value)) {
                var newValue = value.toString().trim();
                data[key] = newValue;
            }
        });
        var emsPort = parseInt(data.emsPort);
        data.emsPort = emsPort;
        var u2kPort = parseInt(data.u2kPort);
        data.u2kPort = u2kPort;

        var url;
        if (e.model.isNew()) {
            url = URLService.getURL('addEmsConfig');
        } else {
            url = URLService.getURL('updateEmsConfig');
        }

        $http.post(url, data).success(function (response) {
            if (response.success) {
                grid.dataSource.read();
            } else {
                Ut.dialog.errMsg(response.errorMsg);
            }
        });
    }

    function _deleteEmxProxy(e) {
        var grid = this;
        Ut.dialog.confirm($scope.i18n.tip.deleteConfirmation, function () {
            var tr = $(e.target).closest('tr');
            var data = grid.dataItem(tr);
            var url = URLService.getURL('deleteEmsConfig');
            $http.post(url, {
                emsId: data.emsId
            }).success(function (response) {
                if (response.success) {
                    Ut.dialog.tip($scope.i18n.tip.delSuccess);
                    grid.dataSource.read();
                } else {
                    Ut.dialog.errMsg(response.errorMsg);
                }
            });
        });

        //返回false页面不发生跳转，执行后还是在页面的当前位置，防止跳转到默认页面  --modify by zhout3517 2017/4/26
        return false;
    }

    //保存参数配置
    function _updateConfigData(e) {
        var data = e.model;
        var grid = e.sender;
        var url = URLService.getURL('updateConfigData');
        $http.post(url, data).success(function (response) {
            if (response.success) {
                grid.dataSource.read();
            } else {
                Ut.dialog.errMsg(response.errorMsg);
            }
        });
    }

    function _dataBoundFun(e) {
        var widget = e.sender;
        var dataItems = widget.dataSource.data();
        var gridId = widget.element.attr('id');
        var appId = gridId.split('_')[1];
        var namespaceId = gridId.split('_')[2];
        var curApp = $scope.modifyItemNum['n' + appId];
        var curGridId = 'n_' + namespaceId;
        if (dataItems.length > 0) {
            //1.循环累加本表格修改项数目
            angular.forEach(dataItems, function (item) {
                if (item.status != 0) {
                    curApp[curGridId]++;
                    //添加指定类修改样式
                    angular.element('[data-uid=' + item.uid + ']').addClass('change-item');
                }
            });

            //2.本应用下所有表格修改项总和清零,重新计算修改项总数
            curApp.sum = 0;
            angular.forEach(curApp, function (index, key) {
                if (key !== 'sum') {
                    curApp.sum += curApp[key];
                }
            });
        }

        //为编辑按钮添加提示
        e.sender.tbody.find('.k-grid-edit').each(function (rowNum, btn) {
            angular.element(btn).attr('title', $scope.i18n.edit);
        });

        //为删除按钮添加提示
        e.sender.tbody.find('.iconFont-delete').each(function (rowNum, btn) {
            angular.element(btn).attr('title', $scope.i18n.deleteEms);
        });

        if ($scope.$$phase != '$digest' && $scope.$$phase != '$apply') {
            //kendoGrid edit mode时点击取消，会执行该回调函数，手动调用$digest避免修改项计数无法更新到视图层
            $scope.$digest();
        }
    }

    //取消编辑事件
    function _cancelFun(e) {
        //新增行点击取消后会调用_dataBoundFun，需清空本表格修改项计数
        if (e.model.isNew()) {
            processModifyItemNum(DEFAULT_PROXY.aid, DEFAULT_PROXY.namespaceId);
        }
        //阻止点击取消按钮的默认行为，cancelRow方法会更新dom行节点，使change-item样式类消失
        e.preventDefault();
        //手动调用取消行方法
        e.sender.cancelRow();
        //根据该行数据，判断是否添加change-item样式类
        var data = e.model;
        if (data.status != 0) {
            angular.element('[data-uid=' + data.uid + ']').addClass('change-item');
        }
    }

    function _emsNameValidation(input) {
        if (input.is("[name='emsName']")) {
            var value = input.val().toString().trim();
            if($scope.lang==='zh'){
                //中文校验是否包含空格
                var chrnum = /\s/;
                if (chrnum.test(value)) {
                    input.attr("data-emsnamevalidation-msg", $scope.i18n.tip.containSpace);
                    return false;
                }
            }
            if (Ut.strUtils.isEmpty(value)) {
                input.attr("data-emsnamevalidation-msg", $scope.i18n.tip.empty);
                return false;
            }
        }
        return true;
    }

    function _u2kNameValidation(input) {
        if (input.is("[name='u2kName']")) {
            var value = input.val().toString().trim();
            var chrnum = /\s/;
            if (chrnum.test(value)) {
                input.attr("data-u2knamevalidation-msg", $scope.i18n.tip.containSpace);
                return false;
            }
            if (Ut.strUtils.isEmpty(value)) {
                input.attr("data-u2knamevalidation-msg", $scope.i18n.tip.empty);
                return false;
            }
        }
        return true;
    }

    function _u2kPwdValidation(input) {
        if (input.is("[name='u2kPwd']")) {
            var value = input.val().toString();
            var chrnum = /\s/;
            if (chrnum.test(value)) {
                input.attr("data-u2kpwdvalidation-msg", $scope.i18n.tip.containSpace);
                return false;
            }
            if (Ut.strUtils.isEmpty(value)) {
                input.attr("data-u2kpwdvalidation-msg", $scope.i18n.tip.empty);
                return false;
            }
            if (value.length > 16) {
                input.attr("data-u2kpwdvalidation-msg", $scope.i18n.tip.passwordLength);
                return false;
            }
        }
        return true;
    }

    function _emsIpValidation(input) {
        if (input.is("[name='emsIp']")) {
            var value = input.val().toString().trim();
            if (Ut.strUtils.isEmpty(value)) {
                input.attr("data-emsipvalidation-msg", $scope.i18n.tip.empty);
                return false;
            }
            if (!(Ut.IPUtils.isIPv6(value) || Ut.IPUtils.isIPv4(value))) {
                input.attr("data-emsipvalidation-msg", $scope.i18n.tip.ipFormatWrong);
                return false;
            }
        }
        return true;
    }

    function _u2kIpValidation(input) {
        if (input.is("[name='u2kIp']")) {
            var value = input.val().toString().trim();
            if (Ut.strUtils.isEmpty(value)) {
                input.attr("data-u2kipvalidation-msg", $scope.i18n.tip.empty);
                return false;
            }
            if (!(Ut.IPUtils.isIPv6(value) || Ut.IPUtils.isIPv4(value))) {
                input.attr("data-u2kipvalidation-msg", $scope.i18n.tip.ipFormatWrong);
                return false;
            }
        }
        return true;
    }

    function _emsPortValidation(input) {
        if (input.is("[name='emsPort']")) {
            var value = input.val();

            if (Ut.strUtils.isEmpty(value)) {
                input.attr("data-emsportvalidation-msg", $scope.i18n.tip.empty);
                return false;
            }

            var chrnum = /^\d*$/;
            if (!chrnum.test(value)) {
                input.attr("data-emsportvalidation-msg", $scope.i18n.tip.portFormatWrong);
                return false;
            }

            if (value < 54351 || value > 54358) {
                input.attr("data-emsportvalidation-msg", $scope.i18n.tip.emsPortRange);
                return false;
            }

        }
        return true;
    }

    function _u2kPortValidation(input) {
        if (input.is("[name='u2kPort']")) {
            var value = input.val();

            if (Ut.strUtils.isEmpty(value)) {
                input.attr("data-u2kportvalidation-msg", $scope.i18n.tip.empty);
                return false;
            }

            var chrnum = /^\d*$/;
            if (!chrnum.test(value)) {
                input.attr("data-u2kportvalidation-msg", $scope.i18n.tip.portFormatWrong);
                return false;
            }

            if (value < 0 || value > 65535) {
                input.attr("data-u2kportvalidation-msg", $scope.i18n.tip.u2kPortRange);
                return false;
            }

        }
        return true;
    }

    //读取配置文件信息
    function _readConfigFileInfo(options) {
        options.success($scope.configFileInfoGridDs);
    }

    function _configFileInfoGridDataBoundFun(e) {
        var widget = e.sender;
        widget.wrapper.find(".icon-btn").each(function (_, wrapper) {
            var td = $(wrapper).parent();
            var level = td.find(".k-icon").length;
            if (level === 2) {
                //子行
                var tr = td.parent();
                //展开后子行tr的class和style都会被更新，故添加特殊属性，方便样式选择器定位
                $(tr).attr('child-item', true);
            }
        });

    }


});
